package com.zhitan.ems.alarm.controller;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhitan.ems.alarm.entity.AlarmRecordsEntity;
import com.zhitan.ems.alarm.service.AlarmRecordsService;
import com.zhitan.ems.alarm.vo.AlarmRecordsVO;
import com.zhitan.ems.alarm.wrapper.AlarmRecordsWrapper;
import com.zhitan.ems.common.annotation.Log;
import com.zhitan.ems.common.core.controller.BaseController;
import com.zhitan.ems.common.core.domain.R;
import com.zhitan.ems.common.enums.BusinessType;
import com.zhitan.ems.common.extra.utils.DateUtil;
import com.zhitan.ems.common.utils.DateUtils;
import com.zhitan.ems.common.utils.StringUtils;
import com.zhitan.ems.framework.core.vo.VPage;
import com.zhitan.ems.framework.core.vo.VQueryKit;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
/**
 * 
 * @author zhitan
 * 
 * @date 2025-09-26 21:25:31
 */
@Api(tags = "报警", value = "报警记录")
@RestController
@RequestMapping("intra/alarm/alarmrecords")
public class AlarmRecordsController extends BaseController{
    @Autowired
    private AlarmRecordsService alarmRecordsService;
    /**
     * 列表
     */
    @ApiOperation(value = "列表", response = VPage.class)
    @ApiImplicitParams({
		        @ApiImplicitParam(name = "name", value = "标题",  paramType = "query", required = false, dataType =  "String"),
		})
    @GetMapping("/browse")
    @PreAuthorize("@ss.hasPermi('alarm:alarmrecords:list')")
    public R<VPage<AlarmRecordsVO>> browse(@RequestParam Map<String, Object> params){
        QueryWrapper<AlarmRecordsEntity> queryWrapper=VQueryKit.getQueryWrapperByMap(params,Arrays.asList("name"), AlarmRecordsEntity.class);
        queryWrapper.orderByDesc("id");
         queryWrapper.like(StringUtils.isNotNull(params.get("name")),"name", params.get("name"));
        IPage<AlarmRecordsEntity> pages = alarmRecordsService.page(VQueryKit.getPage(params), queryWrapper);
        return R.data(AlarmRecordsWrapper.build().toVPageVO(pages));
    }
    @ApiOperation(value = "统计返回 今天，当月，当年报警数量", response = Map.class)
    @GetMapping("/statistics")
    @PreAuthorize("@ss.hasPermi('alarm:alarmrecords:list')")
    public R<Map<String, Object>> statistics(@RequestParam(value="statTime",required = false) String  statTime) throws ParseException {
        Map<String, Object> result = new HashMap<>();
        result.put("todayData", alarmRecordsService.getAlarmStatistics());
        result.put("monthData", alarmRecordsService.getMonthlyAlarmStatistics());
        result.put("yearData", alarmRecordsService.getYearlyAlarmStatistics());
        result.put("allStat", alarmRecordsService.getAlarmStatusStatistics(null,null));
        return R.ok(result);
    }
    @ApiOperation(value = "统计汇总数据:小时,天，月，年", response = Map.class)
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "statTimeType", value = "1,2,3,4", required = true, dataType = "Integer"),
    })
    @GetMapping("/statisticsByTime")
    @PreAuthorize("@ss.hasPermi('alarm:alarmrecords:list')")
    public R<Map<String, Object>> statisticsByTime(@RequestParam(value="statTime",required = false) String  statTime) throws ParseException {
    	Map<String, Object> result = new HashMap<>();
    	if(statTime.length()==10) {
    		 // 获取当前月份的开始和结束时间
            Date curDate =DateUtil.parse(statTime,"yyyy-MM-dd");
            Date start =  DateUtil.getStartOfDate(curDate);
            Date end =  DateUtil.getEndOfDate(curDate);
            result=alarmRecordsService.getAlarmGroupStatistics(start, end, 1);//小时列表
    	}else if(statTime.length()==7) {
    		 // 获取当前月份的开始和结束时间
            Date curDate =DateUtil.parse(statTime,"yyyy-MM");
            Date start =  DateUtil.getStartOfMonth(curDate);
            Date end =  DateUtil.getEndOfMonth(curDate);
            result=alarmRecordsService.getAlarmGroupStatistics(start, end, 2);//天
    	}else if(statTime.length()==4) {
    		 // 获取当前月份的开始和结束时间
            Date curDate =DateUtil.parse(statTime,"yyyy");
            Date start =  DateUtil.getStartOfYear(curDate);
            Date end =  DateUtil.getEndOfYear(curDate);
            result=alarmRecordsService.getAlarmGroupStatistics(start, end, 3);//月
    	}
    	return R.ok(result);
    }

	@ApiOperation(value = "报警等级占比统计信息", response = Map.class)
	@GetMapping("/alarmLevelStatistics")
	@PreAuthorize("@ss.hasPermi('alarm:alarmrecords:list')")
	public R<Map<String, Object>> getAlarmLevelStatistics(
			@RequestParam(value = "statTime", required = false) String statTime) throws ParseException {
		Date today = new Date();
		// 获取最近一个月的开始时间
		Date startDate = DateUtil.getStartOfMonth(DateUtil.addMonths(today, -1));
		Date endOfToday = DateUtil.getEndOfMonth(today);
		if (statTime == null) {
		} else if (statTime.length() == 10) {
			// 获取当前月份的开始和结束时间
			Date curDate = DateUtil.parse(statTime, "yyyy-MM-dd");
			startDate = DateUtil.getStartOfDate(curDate);
			endOfToday = DateUtil.getEndOfDate(curDate);
		} else if (statTime.length() == 7) {
			// 获取当前月份的开始和结束时间
			Date curDate = DateUtil.parse(statTime, "yyyy-MM");
			startDate = DateUtil.getStartOfMonth(curDate);
			endOfToday = DateUtil.getEndOfMonth(curDate);
		} else if (statTime.length() == 4) {
			// 获取当前月份的开始和结束时间
			Date curDate =DateUtil.parse(statTime, "yyyy");
			startDate = DateUtil.getStartOfYear(curDate);
			endOfToday = DateUtil.getEndOfYear(curDate);
		}
		Map<String, Object> statistics = alarmRecordsService.getAlarmLevelStatistics(startDate, endOfToday);
		return R.data(statistics);
	}
    
    @ApiOperation(value = "报警处理状态占比统计信息", response = Map.class)
    @GetMapping("/alarmStatusStatistics")
    @PreAuthorize("@ss.hasPermi('alarm:alarmrecords:list')")
    public R<Map<String, Object>> getAlarmStatusStatistics(@RequestParam(value="statTime",required = false) String  statTime) throws ParseException{
    	Date today = new Date();
		// 获取最近一个月的开始时间
		Date startDate = DateUtil.getStartOfMonth(DateUtil.addMonths(today, -1));
		Date endOfToday = DateUtil.getEndOfMonth(today);
		if (statTime == null) {
		} else if (statTime.length() == 10) {
			// 获取当前月份的开始和结束时间
			Date curDate =DateUtil.parse(statTime, "yyyy-MM-dd");
			startDate = DateUtil.getStartOfDate(curDate);
			endOfToday = DateUtil.getEndOfDate(curDate);
		} else if (statTime.length() == 7) {
			// 获取当前月份的开始和结束时间
			Date curDate = DateUtil.parse(statTime, "yyyy-MM");
			startDate = DateUtil.getStartOfMonth(curDate);
			endOfToday = DateUtil.getEndOfMonth(curDate);
		} else if (statTime.length() == 4) {
			// 获取当前月份的开始和结束时间
			Date curDate = DateUtil.parse(statTime, "yyyy");
			startDate = DateUtil.getStartOfYear(curDate);
			endOfToday = DateUtil.getEndOfYear(curDate);
		}
        Map<String, Object> statistics = alarmRecordsService.getAlarmStatusStatistics(startDate,endOfToday);
        return R.data(statistics);
    }
    /**
     * 信息
     */
    @ApiOperation(value = "信息", response = AlarmRecordsVO.class)
    @GetMapping("/detail/{id}")
    @PreAuthorize("@ss.hasPermi('alarm:alarmrecords:info')")
    public R<AlarmRecordsVO> detail(@PathVariable("id") Long id){
		AlarmRecordsEntity alarmRecords = alarmRecordsService.getById(id);
	    return R.data(AlarmRecordsWrapper.build().entityVO(alarmRecords));
    }
     /**
     * 保存&更新 
     */
    @Log(title = "", businessType = BusinessType.ADDANDEDIT)
    @ApiOperation(value = "保存&更新", response = Boolean.class)
    @PostMapping("/submit")
    @PreAuthorize("@ss.hasPermi('alarm:alarmrecords:save')")
    public R<AlarmRecordsVO> submit(@Valid @RequestBody AlarmRecordsVO alarmRecords){
    	 if(alarmRecords.getId()==null) {
           return add(alarmRecords);
         }else {
           return edit(alarmRecords);
        }
    }
    @Log(title = "", businessType = BusinessType.ADDANDEDIT)
    @ApiOperation(value = "保存&更新", response = Boolean.class)
    @PostMapping("/submitConfirm")
    @PreAuthorize("@ss.hasPermi('alarm:alarmrecords:save')")
    public R<AlarmRecordsVO> submitConfirm(@Valid @RequestBody AlarmRecordsVO alarmRecords){
    	alarmRecords.setAcknowledgedTime(new Date());
    	alarmRecords.setUpdateAt(new Date());
    	if(alarmRecordsService.updateById(alarmRecords)) {
    		 return R.ok(alarmRecords);
    	 }
    	return R.error("数据错误");
    }
    @Log(title = "", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增", response = Boolean.class)
    @PostMapping("/add")
    @PreAuthorize("@ss.hasPermi('alarm:alarmrecords:save')")
    public R<AlarmRecordsVO> add(@Valid @RequestBody AlarmRecordsVO alarmRecords){
   		if(alarmRecords.getId()==null) {
            alarmRecords.setCreateAt(new Date());
            alarmRecords.setIsDelete(0);
            alarmRecords.setUpdateAt(new Date());
        } 
    	if(alarmRecordsService.save(alarmRecords)) {
    		 return R.ok(alarmRecords);
    	 }
    	return R.error("数据错误");
    }
    
    @Log(title = "", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "更新", response = Boolean.class)
    @PostMapping("/edit")
    @PreAuthorize("@ss.hasPermi('alarm:alarmrecords:update')")
    public R<AlarmRecordsVO> edit(@Valid @RequestBody AlarmRecordsVO alarmRecords){
   		alarmRecords.setUpdateAt(new Date());
    	if(alarmRecordsService.updateById(alarmRecords)) {
    		 return R.ok(alarmRecords);
    	 }
    	return R.error("数据错误");
    }
    /**
     * 删除
     */
    @ApiOperation(value = "删除", response = Boolean.class)
    @DeleteMapping("/delete")
    @PreAuthorize("@ss.hasPermi('alarm:alarmrecords:delete')")
    @Log(title = "", businessType = BusinessType.DELETE)
    public R<Boolean> delete(@RequestBody Long[] ids){
        return R.ok(alarmRecordsService.removeByIds(Arrays.asList(ids)));
    }

}